package com.zllkj.mm.api.network;

import android.app.Activity;
import android.text.TextUtils;

import com.zllkj.mm.AppManager;
import com.zllkj.mm.MyApp;
import com.zllkj.mm.common.ClientConfig;
import com.zllkj.mm.common.L;
import com.zllkj.mm.util.KLog;
import com.zllkj.mm.util.common.NetworkUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BaseInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        HttpUrl originalHttpUrl = originalRequest.url();
        String urlStr = originalHttpUrl.url().toString();

        Activity activity = AppManager.getAppManager().currentActivity();

        if (!NetworkUtils.isAvailable(activity)) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    L.showToast("当前无网络!");
                }
            });
        }


     if (urlStr.startsWith(ClientConfig.BASE_URL) && canAddSessionId(urlStr)) {
            HttpUrl url = originalHttpUrl.newBuilder()
                    .addQueryParameter("session_id", MyApp.getInstance().getSessionId())
                    .build();

            KLog.i("sessionId: " + MyApp.getInstance().getSessionId());

            Request request = originalRequest.newBuilder()
                    .url(url)
                    .method(originalRequest.method(), originalRequest.body())
                    .build();

            return chain.proceed(request);
        } else {
            return chain.proceed(originalRequest);
        }
    }



    private boolean canAddSessionId(String urlStr) {
        if (urlStr.contains("login") || urlStr.contains("get_code")
                || urlStr.contains("register") || urlStr.contains("init_info")) {
            return false;
        }

        if (TextUtils.isEmpty(MyApp.getInstance().getSessionId())) {
            return false;
        }

        return true;
    }

}
